Home:ALL Converter>Get "keyInvalid" when requesting Google Custom Search API

Get "keyInvalid" when requesting Google Custom Search API

Ask Time:2017-10-20T14:19:40         Author:Courtney Pruitt

Json Formatter

I am trying to automate search queries re Programmatically searching google in Python using custom search and and keep receiving this error for a simple search:

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "keyInvalid",
    "message": "Bad Request"
   }
  ],
  "code": 400,
  "message": "Bad Request"
 }
}

Here is my code:

import os
import pprint
from googleapiclient.discovery import build

api_key = os.environ.get('API_KEY', None)
cse_id = os.environ.get('CSE_ID', None)


def google_search(search_term, api_key, cse_id, **kwargs):
    service = build("customsearch", "v1", developerKey=api_key)
    res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
    return res['items']


results = google_search(
    'coding', api_key, cse_id, num=3)
for result in results:
    pprint.pprint(result)

I doubled check the API key and have definitely not exceeded usage limits (only ran the program a couple times). I did restrict the API key to my IP address when I initially configured it (not sure if this is a potential cause; am new to API's and just want to test this one safely).

Author:Courtney Pruitt,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/46843359/get-keyinvalid-when-requesting-google-custom-search-api
yy